
import axios from 'axios'
import router from '../../router'
import qs from 'qs' // 直接post请求后台取不到参数,()
import { Dialog } from 'vant';
import { Toast } from 'vant';
import store from "./../../store";
//axios.defaults.baseURL = '/api/'+config.appCode; // 公共请求地址(云部署配置）
// axios.defaults.baseURL = '/russia'  // 单机部署配置
axios.defaults.baseURL = '/api'  // 单机部署配置
// axios.interceptors.request.header('Access-Control-Allow-Headers', 'Content-Type', 'Content-Length', 'Authorization', 'Accept', 'X-Requested-With', 'yourHeaderFeild');
// 发起请求时,会执行该方法

// 默认携带Cookie
axios.defaults.withCredentials=true;
let loadingToast = null;
axios.interceptors.request.use(config => {
    // store.commit('ifLoading', true)
    //NProgressNProgress.start()
    if(store.state.token){
        config.headers.Authorization = store.state.token;
    }
    //你可以在这里开始加载动画,  查询token  等等之类
    loadingToast = Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        duration: 0
    });
    return config
}, err => {
    return Promise.reject(err)
})
//接收到后台的数据时执行的方法
axios.interceptors.response.use(response => {
    loadingToast.clear();
    return response
}, err => {
    //NProgress.done()
    loadingToast.clear();
})
//检查状态码 status
console.log("localStorage.getItem('token'): ",store.state.token)
// 检查状态函数
// 检查状态函数
function checkStatus(res) {
    // store.commit('ifLoading', false)
    //NProgress.done()
    
    loadingToast.clear();
    if(!res){
        router.push('/login')
        return;
    }
    
    if ((res.status === 200 || res.status === 304) && res.data.code == "SUCCESS") { //当状态正常是返回原样的数据
        loadingToast.clear();
        return res.data
    } else {
        console.log('1234res:',res)
        if(res.data.code==='UNAUTHORIZED') {
            Dialog({title:'错误',message: '您登录超时,请重新登录'});
            localStorage.removeItem('token')
        }else if(res.data.code ==='NoAuthException'){
            // MessageBox.alert(res.data.message || res.data.msg, '系统提示',{
            //     confirmButtonText:'确定',
            //     callback: action => {
            //         axios.get(url.logout,{}).then(()=>{
            //             //NProgress.done()
            //             console.log('NoAuthException')
            //             router.push('/ssoLogin')
            //         })
            //     }
            // })
            loadingToast.clear();
            Dialog.alert({
                // title: '错误',
                message: res.data.message || res.data.msg || '未知异常'
            });
        }else{
            Dialog.alert({
                title: '错误',
                message: res.data.message || res.data.msg || '未知异常',
            });
            // Notification.error({
            //     title: '错误',
            //     message: res.data.message || res.data.msg || '未知异常'
            // })
            return false // 状态不正常时可以返回自己自定义的一些格式或者状态什么的
        }

    }
}

export default {
    error(message) {
        Dialog.alert({
            // title: '错误2',
            message: message || '未知异常'
        });
        // Notification.error({
        //     title: '错误',
        //     message: (message || '未知异常')
        // })
        
    },
    file(url, data) {
        if (!url) return
        return axios({
            method: 'post',
            url,
            data,
            headers: {
                'Content-Type': 'multipart/form-data',
                'Local': localStorage.getItem('lang')
            },
            timeout: 10000
        }).then(checkStatus).catch(res => {
            Dialog.alert({
                // title: '错误',
                message: message
            });
            // Notification.error({
            //     title: '错误',
            //     message: res
            // })
            return false
        })
    },
    success(message) {
        loadingToast.clear();
        Dialog.alert({
            title: '成功',
            message: message || '操作成功'
        });
        // Notification.success({
        //     title: '成功',
        //     message: (message || '操作成功')
        // });
    },
    get(url, params = {}) { //返回封装后的 get 方法
        if (!url) return
        //params.access_token = store.getters.AppInfo.accessToken;
        return axios({
            method: 'get',
            url,
            params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                accessToken: localStorage.getItem("token"),
                'Local': localStorage.getItem('lang')
                //'content-type': 'application/json;charset=UTF-8'
            },
            timeout: 10000
        }).then(checkStatus).catch(res => {
            loadingToast.clear();
            Dialog.alert({
                title: '',
                message: res
            });
            //store.commit('ifLoading', false)

            // Notification.error({
            //     title: '错误',
            //     message: res
            // })
            return false
        })
    },
    post(url, data = {}) { //返回封装后的 post 方法
        if (!url) return
        // if(url != '/merchant/login/signIn'){
        //     data.access_token = store.getters.AppInfo.accessToken;
        // }
        //data.access_token = store.getters.AppInfo.accessToken;
        return axios({
            method: 'post',
            url,
            data,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                accessToken: localStorage.getItem('token'),
                'Local': localStorage.getItem('lang')
            },
            timeout: 10000
        }).then(checkStatus).catch(res => {
            loadingToast.clear();
            Dialog.alert({
                title: '',
                message: res
            });
            return false
        })
    },
    delete(url, data = {}) { //返回封装后的 post 方法
        if (!url) return
        // if(url != '/merchant/login/signIn'){
        //     data.access_token = store.getters.AppInfo.accessToken;
        // }
        //data.access_token = store.getters.AppInfo.accessToken;
        return axios({
            method: 'delete',
            url,
            data,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                accessToken: localStorage.getItem('token'),
                'Local': localStorage.getItem('lang')
            },
            timeout: 10000
        }).then(checkStatus).catch(res => {
            loadingToast.clear();
            Dialog.alert({
                title: '',
                message: res
            });
            return false
        })
    },
    put(url, data = {}) { //返回封装后的 post 方法
        if (!url) return
        // if(url != '/merchant/login/signIn'){
        //     data.access_token = store.getters.AppInfo.accessToken;
        // }
        //data.access_token = store.getters.AppInfo.accessToken;
        return axios({
            method: 'put',
            url,
            data,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                accessToken: localStorage.getItem('token'),
                'Local': localStorage.getItem('lang')
            },
            timeout: 10000
        }).then(checkStatus).catch(res => {
            loadingToast.clear();
            Dialog.alert({
                title: '',
                message: res
            });
            return false
        })
    }
}
